package com.xuanzheng.company.dao.impl;

import com.xuanzheng.company.dao.CompanyDao;
import com.xuanzheng.company.entity.Company;
import com.xuanzheng.company.util.DBUtil;
import com.xuanzheng.company.util.IdGenerator;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CompanyDaoImpl implements CompanyDao {

    @Override
    public boolean addCompany(Company company) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean result = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO company (id, name, address, phone, credit_code, manager_id, employee_count, status) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql);

            // 生成唯一ID
            String id = IdGenerator.generateId();
            company.setId(id);

            pstmt.setString(1, company.getId());
            pstmt.setString(2, company.getName());
            pstmt.setString(3, company.getAddress());
            pstmt.setString(4, company.getPhone());
            pstmt.setString(5, company.getCreditCode());
            pstmt.setString(6, company.getManagerId());
            pstmt.setInt(7, company.getEmployeeCount());
            pstmt.setInt(8, company.getStatus());

            int affectedRows = pstmt.executeUpdate();
            result = (affectedRows > 0);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }

        return result;
    }

    @Override
    public Company getCompanyById(String id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Company company = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM company WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, id);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                company = mapResultSetToCompany(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return company;
    }

    @Override
    public Company getCompanyByCreditCode(String creditCode) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Company company = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM company WHERE credit_code = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, creditCode);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                company = mapResultSetToCompany(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return company;
    }

    @Override
    public Company getCompanyByManagerId(String managerId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Company company = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM company WHERE manager_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, managerId);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                company = mapResultSetToCompany(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return company;
    }

    @Override
    public boolean updateEmployeeCount(String companyId, int increment) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean result = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE company SET employee_count = employee_count + ? WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, increment);
            pstmt.setString(2, companyId);

            int affectedRows = pstmt.executeUpdate();
            result = (affectedRows > 0);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }

        return result;
    }

    @Override
    public List<Company> getAllCompanies() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Company> companies = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM company ORDER BY create_time DESC";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                Company company = mapResultSetToCompany(rs);
                companies.add(company);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return companies;
    }

    @Override
    public String getNextEmployeeNumber(String companyId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String nextEmployeeNumber = "00001"; // 默认从00001开始

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT MAX(CAST(employee_number AS UNSIGNED)) AS max_number FROM company_employee " +
                    "WHERE company_id = ? AND status = 1";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, companyId);
            rs = pstmt.executeQuery();

            if (rs.next() && rs.getString("max_number") != null) {
                int maxNumber = rs.getInt("max_number");
                int nextNumber = maxNumber + 1;
                nextEmployeeNumber = String.format("%05d", nextNumber); // 格式化为5位数
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return nextEmployeeNumber;
    }

    @Override
    public boolean updateCompanyStatus(String id, int status) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean result = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE company SET status = ? WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, status);
            pstmt.setString(2, id);

            int affectedRows = pstmt.executeUpdate();
            result = (affectedRows > 0);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }

        return result;
    }

    // 辅助方法：将ResultSet映射到Company对象
    private Company mapResultSetToCompany(ResultSet rs) throws SQLException {
        Company company = new Company();
        company.setId(rs.getString("id"));
        company.setName(rs.getString("name"));
        company.setAddress(rs.getString("address"));
        company.setPhone(rs.getString("phone"));
        company.setCreditCode(rs.getString("credit_code"));
        company.setManagerId(rs.getString("manager_id"));
        company.setEmployeeCount(rs.getInt("employee_count"));
        company.setStatus(rs.getInt("status"));
        company.setCreateTime(rs.getTimestamp("create_time"));
        company.setUpdateTime(rs.getTimestamp("update_time"));
        return company;
    }
} 